package com.dousb.cloudlibrary.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dousb.cloudlibrary.annotation.AuthCheck;
import com.dousb.cloudlibrary.common.BaseResponse;
import com.dousb.cloudlibrary.common.DeleteRequest;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.common.ResultUtils;
import com.dousb.cloudlibrary.constant.UserConstant;
import com.dousb.cloudlibrary.exception.BusinessException;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.model.dto.book.BookAddRequest;
import com.dousb.cloudlibrary.model.dto.book.BookCategory;
import com.dousb.cloudlibrary.model.dto.book.BookQueryRequest;
import com.dousb.cloudlibrary.model.dto.book.BookUpdateRequest;
import com.dousb.cloudlibrary.model.entity.Book;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.BookVO;
import com.dousb.cloudlibrary.service.BookService;
import com.dousb.cloudlibrary.service.UserService;
import com.dousb.cloudlibrary.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 图书表接口
 */
@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {

    @Resource
    private BookService bookService;

    @Resource
    private UserService userService;

    @Resource
    private CacheUtil cacheUtil;

    // region 增删改查

    /**
     * 创建图书
     *
     * @param bookAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addBook(@RequestBody BookAddRequest bookAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(bookAddRequest == null, ErrorCode.PARAMS_ERROR);
        Book book = new Book();
        BeanUtils.copyProperties(bookAddRequest, book);
        // 数据校验
        bookService.validBook(book, true);
        // 写入数据库
        boolean result = bookService.save(book);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newBookId = book.getBook_id();
        return ResultUtils.success(newBookId);
    }

    /**
     * 删除图书
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteBook(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = bookService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新图书（仅管理员可用）
     *
     * @param bookUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBook(@RequestBody BookUpdateRequest bookUpdateRequest) {
        if (bookUpdateRequest == null || bookUpdateRequest.getBook_id() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookUpdateRequest, book);
        // 数据校验
        bookService.validBook(book, false);
        // 判断是否存在
        long id = bookUpdateRequest.getBook_id();
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = bookService.updateById(book);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 bookId 获取图书表（封装类）
     *
     * @param book_id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BookVO> getBookVOById(Long book_id, HttpServletRequest request) {
        ThrowUtils.throwIf(book_id == null || book_id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Book book = bookService.getById(book_id);
        ThrowUtils.throwIf(book == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(bookService.getBookVO(book, request));
    }

    /**
     * 分页获取图书表列表（仅管理员可用）
     *
     * @param bookQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Book>> listBookByPage(@RequestBody BookQueryRequest bookQueryRequest) {
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 查询数据库
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        return ResultUtils.success(bookPage);
    }

    /**
     * 分页获取图书表列表（封装类）
     * redis缓存
     *
     * @param bookQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BookVO>> listBookVOByPage(@RequestBody BookQueryRequest bookQueryRequest,
                                                       HttpServletRequest request) {
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        String queryCondition = JSONUtil.toJsonStr(bookQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = "douBook:listBookVOByPage" + hashKey;
        String cachedValue = cacheUtil.get(redisKey);
        if (cachedValue != null) {
            Page<BookVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 查询数据库
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        // 获取封装类
        //获取封装类
        Page<BookVO> bookVOPage = bookService.getBookVOPage(bookPage, request);
        //存入redis
        String cacheValue = JSONUtil.toJsonStr(bookVOPage);
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        cacheUtil.set(redisKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
        return ResultUtils.success(bookVOPage);
    }
    // endregion

    /**
     * 获取图书分类
     *
     * @return BaseResponse<BookVO>
     * @author 豆沙包
     * @date 2025/9/23 19:36
     */
    @GetMapping("/tag_category")
    public BaseResponse<BookCategory> getTagCategory() {
        BookCategory bookCategory = new BookCategory();
        List<String> categoryList = Arrays.asList("人文社科类", "文学小说类", "自然科学与技术类", "应用技能类", "生活休闲类", "艺术与创意类");
        bookCategory.setBook_category(categoryList);
        return ResultUtils.success(bookCategory);
    }

    /**
     * 借阅图书排行榜（按借阅次数排序）
     *
     * @return 借阅量前20的图书列表
     */
    @GetMapping("/hot/list")
    public BaseResponse<List<BookVO>> getHotBookList(HttpServletRequest request) {
        // 创建查询条件，按借阅次数降序排列
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("record_count");
        List<Book> hotBookList = bookService.list(queryWrapper.last("limit 20"));
        List<BookVO> bookVOList = hotBookList.stream()
                .map(book -> bookService.getBookVO(book, request))
                .collect(Collectors.toList());
        return ResultUtils.success(bookVOList);
    }
}
